package com.scedu.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import sun.plugin2.applet.context.NoopExecutionContext;

import java.net.PasswordAuthentication;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean //加密规则
    public PasswordEncoder mypasswordEncoder(){
        //2.加密规则
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //3、授权规则

        //首页所有人可以访问，功能页只有对应有权限的人才能访问
        //链式编程
        http
                .csrf().disable() //避免csrf出错
                .authorizeRequests() //开启登录配置
                //.antMatchers("/index/").permitAll()   //表示访问 /index 这个接口，所有角色都可以
//                .antMatchers("/level1/**").hasRole("vip1") //基于角色
//                .antMatchers("/level2/**").hasRole("vip2")//表示访问 /level1 这个接口，需要具备 vip1 这个角色
//                .antMatchers("/level3/**").hasRole("vip3")
                .antMatchers("/level1/**").hasAnyAuthority("p1","p2") //基于权限
                .antMatchers("/level2/**").hasAnyAuthority("p2")//表示访问 /level1 这个接口，需要具备 vip1 这个权限
                .antMatchers("/level3/**").hasAnyAuthority("p3")
                .anyRequest().permitAll() //除了以上都可以访问
                //.antMatchers("/index").hasAnyRole();//表示/index这个页面需要登录
                .and()
                .formLogin() //允许表单登录
                .loginPage("/toLogin")  //定义登录页面，
                .loginProcessingUrl("/login")      // 定义登录接口
                .successForwardUrl("/index") //定义登录成功页面
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) //SESSION策略
                .and()
                .logout()  //4.注销规则
                .logoutUrl("/logout")
                .logoutSuccessUrl("/index");
    }


}
